package com.xgkj.diyiketang.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.CommentAdapter;
import com.xgkj.diyiketang.data.CommentInfo;
import com.xgkj.diyiketang.data.SchoolReportDeailInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.CommentListTask;
import com.xgkj.diyiketang.task.PublishCommentTask;
import com.xgkj.diyiketang.task.ReportDeailInfoTask;
import com.xgkj.diyiketang.task.ShouCangTask;
import com.xgkj.diyiketang.task.ZanDiaryTask;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.ShareUtil;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.MyCustomListView;
import com.xgkj.diyiketang.weidget.MyLoadDataListView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/*
 * 校报详情
 */

public class SchoolReportDeailActivity extends BaseActivity implements MyLoadDataListView.LoadDataListener, View.OnClickListener {

    private MyLoadDataListView myLoadDataListView;
    private View headerView;
    private RelativeLayout back, share_bt;
    private LinearLayout school_report_shade, report_detail_zan,shoucang;
    private int currentPage = 1;
    private int commentListTaskId = -1;
    private CommentAdapter cmtAdapter;
    private String rid, name, haveUp,isCollection;//校报id
    private MyCustomListView commentList;
    private int publishCmtTaskId = -1;
    private String cmtText;
    private ClearableEditText cmtContant;
    private Button btn;//发送
    private int reportdeailTaskId = -1;
    private TextView title;
    private TextView time;
    private TextView author;
    private TextView looknumber;
    private TextView content,shoucang_text;
    private ImageView detailimg, zan_hui,shoucang_img,load_animation;
    private SchoolReportDeailInfo deailInfo;
    private TextView laud;
    private int zanTaskId = -1;
    private int shoucangTaskId = -1;
    String zan_count = "0";//从服务器得到赞的数量
    private LinearLayout schoolReportLayout,load_layout;
    private AnimationDrawable animation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_school_report_deail);
        rid = getIntent().getStringExtra("rid");
        name = getIntent().getStringExtra("name");
        haveUp = getIntent().getStringExtra("haveUp");
        isCollection = getIntent().getStringExtra("isCollection");
        initView();
        updataDeailInfo();
        getCommentList();
    }

    private void initView() {

        school_report_shade = (LinearLayout) findViewById(R.id.school_report_shade);
        myLoadDataListView = (MyLoadDataListView) findViewById(R.id.reportdetail_listview);
        cmtContant = (ClearableEditText) findViewById(R.id.reportdetail_cet);
        btn = (Button) findViewById(R.id.reportdetail_btn);
        back = (RelativeLayout) findViewById(R.id.reportdetail_back);
        share_bt = (RelativeLayout) findViewById(R.id.share_bt);
        headerView = LayoutInflater.from(this).inflate(R.layout.schoolreportdetailheader, null);
        report_detail_zan = (LinearLayout) headerView.findViewById(R.id.report_detail_zan);
        shoucang = (LinearLayout) headerView.findViewById(R.id.shoucang);
        schoolReportLayout = (LinearLayout) headerView.findViewById(R.id.school_report_detail_header);
        zan_hui = (ImageView) headerView.findViewById(R.id.zan_img);
        shoucang_img = (ImageView) headerView.findViewById(R.id.shoucang_img);
        time = (TextView) headerView.findViewById(R.id.report_detail_time);
        title = (TextView) headerView.findViewById(R.id.reportdetail_title_text);
        detailimg = (ImageView) headerView.findViewById(R.id.reportdetail_img);
        content = (TextView) headerView.findViewById(R.id.reportdetail_content);
        author = (TextView) headerView.findViewById(R.id.reportdetail_author);
        author.setText(name);
        looknumber = (TextView) headerView.findViewById(R.id.reportdetail_looknumber);
        laud = (TextView) headerView.findViewById(R.id.report_detail_laud);
        load_layout = (LinearLayout) headerView.findViewById(R.id.load_layout);
        load_animation = (ImageView)headerView.findViewById(R.id.image_animation_aa);
        animation = (AnimationDrawable)load_animation.getBackground();
        cmtAdapter = new CommentAdapter(this, rid, 1);
        myLoadDataListView.setOnLoadDataListener(this);
        myLoadDataListView.addHeaderView(headerView);
        myLoadDataListView.setAdapter(cmtAdapter);
        btn.setOnClickListener(this);
        back.setOnClickListener(this);
        share_bt.setOnClickListener(this);
        report_detail_zan.setOnClickListener(this);
        shoucang.setOnClickListener(this);
        if (haveUp.equals("0")) {

        } else {
            report_detail_zan.setClickable(false);
            zan_hui.setImageResource(R.drawable.zan_checked);
        }
        if (isCollection.equals("0")){
            shoucang_img.setImageResource(R.drawable.shoucang_unchecked);
        }else {
            shoucang_img.setImageResource(R.drawable.shoucang_checked);
        }

    }

    private void getCommentList() {
        if (currentPage == 0) {
            myLoadDataListView.setNoNextPage();
            return;
        }
        animation.start();
        CommentListTask cmtListTask = new CommentListTask(10, currentPage, rid);
        cmtListTask.addListener(mListener);
        commentListTaskId = getEatShowApp().getTaskManager().addTask(cmtListTask);

    }

    private void updataDeailInfo() {
        //cmtText = cmtContant.getText().toString().trim();
        ReportDeailInfoTask rdTask = new ReportDeailInfoTask(rid);
        rdTask.addListener(mListener);
        reportdeailTaskId = getEatShowApp().getTaskManager().addTask(rdTask);
    }

    private void publishComment() {
        //cmtText = cmtContant.getText().toString().trim();
        PublishCommentTask pcTask = new PublishCommentTask(rid, cmtText, "", "");
        pcTask.addListener(mListener);
        publishCmtTaskId = getEatShowApp().getTaskManager().addTask(pcTask);
    }

    private TaskEventListener mListener = new ShowToastTaskEventListener(this) {

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == publishCmtTaskId) {
                Toast.makeText(mContext, R.string.pinglun_success, Toast.LENGTH_SHORT).show();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(cmtContant.getWindowToken(), 0);
                cmtContant.setText("");
                currentPage = 1;
                getCommentList();
            } else if (taskId == commentListTaskId) {
                if (data != null) {
                    List<CommentInfo> list = (List<CommentInfo>) data;
                    if (currentPage == 1) {
                        cmtAdapter.clearData();
                        myLoadDataListView.enableLoadMore();
                    }
                    if (list != null && list.size() > 0) {
                        cmtAdapter.updateData(list);
                    }
                    currentPage = result;
                }
            } else if (taskId == reportdeailTaskId) {
                if (data != null) {
                    schoolReportLayout.setVisibility(View.VISIBLE);
                    deailInfo = (SchoolReportDeailInfo) data;
                    try {
                        if (deailInfo.getDairyTitle() != null) {
                            title.setText(" " + URLDecoder.decode(deailInfo.getDairyTitle(), "utf-8"));
                        }
                        if (deailInfo.getDairyTime() != null) {
                            time.setText(URLDecoder.decode(deailInfo.getDairyTime(), "utf-8"));
                        }
                        if (deailInfo.getViewCount() != null) {
                            looknumber.setText(URLDecoder.decode(deailInfo.getViewCount(), "utf-8"));
                        }
                        if (deailInfo.getDairyContent() != null) {
                            content.setText(URLDecoder.decode(deailInfo.getDairyContent(), "utf-8"));
                        }
                        if (deailInfo.getUpCount() != null) {
                            zan_count = URLDecoder.decode(deailInfo.getUpCount(), "utf-8");
                            laud.setText(zan_count);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    animation.stop();
                    load_layout.setVisibility(View.GONE);
                    String dairyImgUrl = deailInfo.getDairyImage();

                    if (dairyImgUrl != null && dairyImgUrl.length() > 0) {
                        ViewUtil.Size size = ViewUtil.getHeadImageSize_40(mContext);
                        Bitmap cacheBitmap = ImageCache.getInstance(mContext).getBitmapFromMemoryCache(ImageCache.getInstance(mContext).getCacheKey(dairyImgUrl, size));
                        if (cacheBitmap != null) {
                            detailimg.setImageBitmap(cacheBitmap);
                        } else {
//                            detailimg.setImageResource(R.drawable.default_food);
                            ImageCache.getInstance(mContext).loadBitmapToView(detailimg, dairyImgUrl, size);
                        }
                    }
                }else {

                    schoolReportLayout.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == reportdeailTaskId){
                ToastUtil.showMessage(SchoolReportDeailActivity.this,"加载失败");
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    @Override
    public void onLoadMore() {
        getCommentList();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reportdetail_back:
                finish();
                break;
            case R.id.reportdetail_btn:
                if (checkInput()) {
                    publishComment();
                    cmtContant.setText(null);
                }
                break;
            case R.id.share_bt:
                String share_title = null;
                try {
                    if (deailInfo.getDairyContent() != null) {
                        share_title = (URLDecoder.decode(deailInfo.getDairyContent(), "utf-8"));
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                String myuserId = null;
                String share_url = "http://115.28.236.67:8096/classroom/dariy.html?diaryId=" + rid;
                // PalLog.e("share_url",share_url);
                ShareUtil.getInstance(mContext).show(share_title, share_url, new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        school_report_shade.setVisibility(View.GONE);
                    }
                }, v);
                break;
            case R.id.report_detail_zan:

                if (getEatShowApp().getmUserInfo() != null) {
                    ZanDiaryTask dtask = new ZanDiaryTask(rid);
                    dtask.addListener(new VideoDetailTaskListener(mContext));
                    zanTaskId = getEatShowApp().getTaskManager().addTask(dtask);
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
            case R.id.shoucang:
                if (getEatShowApp().getmUserInfo() != null) {
                    ShouCangTask scTask = new ShouCangTask(rid, isCollection, "1");
                    scTask.addListener(new VideoDetailTaskListener(mContext));
                    shoucangTaskId = getEatShowApp().getTaskManager().addTask(scTask);
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
        }
    }

    class VideoDetailTaskListener extends ShowToastTaskEventListener {

        public VideoDetailTaskListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == zanTaskId) {
                report_detail_zan.setClickable(false);
                zan_hui.setImageResource(R.drawable.zan_checked);
                int zan_count_int = Integer.parseInt(zan_count) + 1;
                laud.setText(zan_count_int + "");
            }else if(taskId == shoucangTaskId) {

                if (isCollection.equals("0")){
                    isCollection = "1";
                    shoucang_img.setImageResource(R.drawable.shoucang_checked);
                }else {
                    isCollection = "0";
                    shoucang_img.setImageResource(R.drawable.shoucang_unchecked);
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    private boolean checkInput() {
        cmtText = cmtContant.getText().toString().trim();

        if (TextUtils.isEmpty(cmtText)) {
            Toast.makeText(mContext, R.string.no_cmt, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
}
